/**
 * 设置缓存数据
 * @param {*} key 缓存key
 * @param {*} value 缓存值
 * @param {*} expiration 过期时间，单位秒 30 * 24 * 60 * 60 * 1000
 */
export function setStorage (key, value, expiration = 2592000000) {
    localStorage.setItem(key, value)
    localStorage.setItem(`${key}_expiration`, Date.now() + expiration)
}

/**
 * 获取缓存数据
 * 如果过期或者不存在，则返回空字符串
 * @param {*} key 缓存key
 */
export function getStorage (key) {
    const expirationKey = `${key}_expiration`
    const timespan = Date.now()
    const value = localStorage.getItem(key)
    const valueExpiration = +localStorage.getItem(expirationKey) || 0
    if (value && timespan < valueExpiration) {
        return value
    }

    localStorage.removeItem(key)
    localStorage.removeItem(expirationKey)
    return ''
}

/**
 * 清除缓存数据
 * @param {*} key 缓存key
 */
export function removeStorage (key) {
    const expirationKey = `${key}_expiration`
    localStorage.removeItem(key)
    localStorage.removeItem(expirationKey)
}
